<?php
namespace Tbf\Bundle\DatabaseBundle\Orm;
use Doctrine\ORM\EntityManager;
use Tbf\Bundle\SerializerBundle\Serializer;
use Tbf\Component\Arrays\ArrayFunction;
use Tbf\Component\Arrays\ArrayReaderInterface;

/**
 * use a doctrine orm iterator get obj ,
 *   then detach it,
 *   then serialize to array
 */
class OrmIteratorSerializeArrayReader implements ArrayReaderInterface{
    /** @var \Doctrine\ORM\EntityManager  */
    protected $em;
    /** @var \Tbf\Bundle\SerializerBundle\Serializer  */
    protected $serializer;
    /** @var \Iterator  */
    protected $iterator;
    /** @var  string */
    protected $serialize_group=null;
    function __construct(EntityManager $em,Serializer $serializer){
        $this->em = $em;
        $this->serializer = $serializer;
    }
    public function setIterator(\Iterator $iterator){
        $this->iterator = $iterator;
        $this->iterator->rewind();
        return $this;
    }
    public function setSerializeGroup($group){
        $this->serialize_group = $group;
        return $this;
    }
    /**
     * 读出一个一维array数组
     * 如果返回值为null表示没有数据了
     * @return array data 数据
     */
    public function readRow()
    {
        if (!$this->iterator->valid()){
            return null;
        }
        $obj = $this->iterator->current();
        if (is_array($obj)){
            $obj = ArrayFunction::firstValue($obj);
        }
        $this->iterator->next();
        $this->em->detach($obj);
        return $this->serializer->toArray($obj,$this->serialize_group);
    }

}